<?php
class M_users extends MY_Model {
	
	private $last_insert_id;

	public function verify_user($post)
	{
		
		$date[] = $post['username']['month'];
		$date[] = $post['username']['day'];
		$date[] = $post['username']['year'];
		$lname = $post['lastname'];
		$pass = $post['studentpassword'];

		$dob = DateTime::createFromFormat('m/d/Y',implode('/',$date))->format('Y-m-d');

		$select_profile = 'SELECT firstname,lastname,middlename,e_student_id,e_profile_id,e_id,user_id FROM profiles p
						   LEFT JOIN enrollments e ON e.e_profile_id = p.profile_id
						   WHERE dob = ? AND lastname = ?
						   AND e.registrar_approved = 1
						   AND e.verified = 1
						   LIMIT 1';
		$res = $this->db->query($select_profile,[$dob,$lname]);

		// pd($res->result());
		if($res->num_rows() >=1 )
		{
			$row = $res->row();
			// vd($this->verify_password($pass,$row->user_id,'student'));
				
			if($this->verify_password($pass,$row->user_id,'student'))
			{
				
				$userdata = array(
					'userid' => $row->e_profile_id,
					'id_e' => $row->e_id,
					'username' => $row->e_student_id,
					'userType' => 'student',
					'e_f_name' => $row->firstname,
					'e_l_name' => $row->lastname,
					'e_m_name' => $row->middlename,
					'logged_in' => TRUE
				);
				
				$this->session->set_userdata($userdata);
				return true;

			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}
	}
	
	/* 	
		-------------------------------------------------------------------
		hash_password
		12-6-12
		perry
		-------------------------------------------------------------------
		hashes the users password
		
		returns the hashed password with salt
	*/
	public function hash_password($password)
	{
		$this->load->helper('passwordcompat');
		return password_hash($password,PASSWORD_BCRYPT);
	}

	/* 	
		-------------------------------------------------------------------
		validate_password
		12-6-12
		perry
		-------------------------------------------------------------------
		validates the users password
		
		returns the hashed password with salt
	*/
	public function validate_password($hashed_password, $password)
	{
		$this->load->helper('passwordcompat');
		return password_verify($password, $hashed_password);
	}
	
	public function change_pass($oldpassword,$newpassword,$id,$type = NULL)
	{

		if($this->verify_password($oldpassword,$id,$type))
		{
			$newpassword = $this->hash_password($newpassword);
			$this->db->set('hashed_password',$newpassword)->where('id',$id)->update('users');
			if($this->db->affected_rows() >= 1)
			{
				$message = (object)array('stat'=>TRUE,'log'=>'Change Password successfull.');
				$this->load->model('M_enrollees');
				$this->M_enrollees->_update_to_username_password_table($id, $password, $type);
				return $message;
			}else{
				$message = (object)array('stat'=>FALSE,'log'=>'Unable to change password.');
				return $message;
			}
		}else{
			$message = (object)array('stat'=>FALSE,'log'=>'Incorrect Old Password');
			return $message;
		}
	}
	
	/*
	--------------------------------------------------------------------------
	verify_password
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	@param old password
	checks password from database and matches from user input
	*/	
	public function verify_password($password,$id,$type='student')
	{
		$data = $this->db->select('hashed_password')
						 ->where('id',$id)
						 ->where('userType',$type)
						 ->limit(1)
						 ->get('users');
		// pd($this->db->last_query());
		// pd($data->row());
		if($data->num_rows() >= 1 )
		{
			$h_pass = $data->row()->hashed_password;

			if($this->validate_password($h_pass,$password)){
				return TRUE;	
			}else{
				return FALSE;
			}
		}else{
			return FALSE;
		}

	}
	
	public function get_last_insert_id()
	{
		return $this->last_insert_id;
	}

	public function verify_parent($post)
	{
		
		$_user_name = $post['parent_username'];
		$_user_pass = $post['parent_password'];

		$parent_cred = $this->db->where('username',$_user_name)
										->where('userType','user')
										->limit(1)
									   ->get('users');
		
		if($parent_cred->num_rows() >=1 )
		{
			$par = $parent_cred->row();
			if($par->userStatus == 'inactive')
			{
				$stat = ['status'=>false,'log'=>'User login is currently disabled please contact school registrar '];

			}else{
				if($this->verify_password($_user_pass,$par->id,'user'))
				{
					$userdata = array(
						'userid' => $par->id,
						'id_e' => '',
						'username' => $_user_name,
						'userType' => 'guardian',
						'e_f_name' => '',
						'e_l_name' => '',
						'e_m_name' => '',
						'logged_in' => TRUE
					);
					
					$this->session->set_userdata($userdata);
					$stat = ['status'=>true,'log'=>'Login successful'];

				}else{
					$stat = ['status'=>false,'log'=>'Wrong Username password combination.'];
				}
			}
		}else{
			$stat = ['status'=>false,'log'=>'Wrong Username password combination.'];
		}

		return (object)$stat;
	}

	public function change_username($post,$id, $usertype = 'student')
	{	
		if($this->verify_password($post['user_password'],$id,'user')){
			$this->db->set('username',$post['new_username'])->where('id',$id)->limit(1)->update('users');
			if($this->db->affected_rows() >=1 )
			{
				$stat = ['status'=>true,'log'=>'Username Successfully updated, log in to refresh changes.'];
			}else{
				$stat = ['status'=>false,'log'=>'Unable to change parent username.'];	
			}
		}else{
			$stat = ['status'=>false,'log'=>'Wrong Password'];
		}

		return (object)$stat;
	}

	/**
	 * Verify User Email
	 * 
	 * During the forgot password should verify if email is in the database
	 *
	 * @param email string
	 * @param usertype string student/parent
	 * @return object 
	 */
	public function verify_user_email($email = false, $usertype = false)
	{
		$sly = new StdClass;
		$sly->status = false;
		$sly->data = false;

		if($email !== false || $usertype !== false){

			if($usertype === "student"){

				$sql = "
					SELECT 
					u.id,
					p.`email`,
					u.username,
					concat(p.firstname,' ',p.lastname) as fullname
					FROM users u
					LEFT JOIN `profiles` p ON u.id = p.`user_id`
					WHERE u.userType = 'student'
					AND p.`email` = ?;
				";
			}

			if($usertype === "parent"){
				$sql = "
					SELECT 
					id,
					username as email,
					username as username
					FROM users
					WHERE username = ?
					AND userType = 'user'
				";
			}

			$q = $this->db->query($sql, [$email]);

			if($q->num_rows() > 0){

				$sly->status = TRUE;
				$sly->data = $q->result();

				return $sly;
			}
		}

		return $sly;
	}

	/**
	 * username check
	 */
	public function username_check($username = false, $except_id = false)
	{
		if($except_id){
			$this->db->where('id <> ', $except_id);
		}
		
		$this->db->select('username');
		$this->db->where('username', $username);
		$q = $this->db->get('users');
		
		return $q->num_rows() > 0 ? false : true;
	}
}
?>